package com.miao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miao.base.exception.XueChengPlusException;
import com.miao.dto.AddCourseDto;
import com.miao.dto.CourseBaseInfoDto;
import com.miao.dto.EditCourseDto;
import com.miao.mapper.*;
import com.miao.pojo.*;
import com.miao.service.ICourseBaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements ICourseBaseService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper categoryMapper;
    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;
    @Autowired
    private TeachplanMapper teachplanMapper;

    @Transactional
    @Override
    public void deleteCourse(Long comId, Long id) {
        //只能删除本机构的
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if(!courseBase.getCompanyId().equals(comId)){
            XueChengPlusException.cast("本机构只能删除本机构课程！！");
        }
        //删除课程教师信息
        LambdaQueryWrapper<CourseTeacher> teacherQuery = new LambdaQueryWrapper<>();
        teacherQuery.eq(CourseTeacher::getCourseId,id);
        courseTeacherMapper.delete(teacherQuery);
        //删除课程视频
        LambdaQueryWrapper<TeachplanMedia> teachplanMediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanMediaLambdaQueryWrapper.eq(TeachplanMedia::getCourseId,id);
        teachplanMediaMapper.delete(teachplanMediaLambdaQueryWrapper);
        //删除课程计划
        LambdaQueryWrapper<Teachplan> teachplanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teachplanLambdaQueryWrapper.eq(Teachplan::getCourseId,id);
        teachplanMapper.delete(teachplanLambdaQueryWrapper);
        //删除课程基本信息
        courseBaseMapper.deleteById(id);
        //删除课程market信息
        courseMarketMapper.deleteById(id);
    }

    @Transactional
    @Override//向课程基本信息表写入数据，向营销表写入数据（价格信息）
    public CourseBaseInfoDto addBase(Long companId, AddCourseDto addCourseDto) {
        //base表--------------------------------
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto, courseBase);//属性名称一致就可以拷贝
        //塞进去id
        courseBase.setCompanyId(companId);
        //时间
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setChangeDate(LocalDateTime.now());
        //审核状态未提交
        courseBase.setAuditStatus("202002");
        //发布状态未发布
        courseBase.setStatus("203001");
        int insert = courseBaseMapper.insert(courseBase);
        if(insert <= 0)throw new RuntimeException("添加异常");
        //market表------------------------------------
        //两个表的联系是：相同的课程对应的主键id一样
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        courseMarket.setId(courseBase.getId());//设置相同的主键
        //保存营销信息
        saveMarket(courseMarket);
        //返回目标信息
        return getCourseInfoDto(courseBase.getId());
    }


    //返回添加成功后前端看的信息，即通过id或许课程信息，以及market信息，合成一个DTO
    @Transactional
    @Override
    public CourseBaseInfoDto getCourseInfoDto(Long id) {
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if(courseBase == null)return null;
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        //将大分类名称小分类名称写进去（数据库没有这个字段）
        String mtName = categoryMapper.selectById(courseBaseInfoDto.getMt()).getName();
        String stName = categoryMapper.selectById(courseBaseInfoDto.getSt()).getName();
        courseBaseInfoDto.setMtName(mtName);
        courseBaseInfoDto.setStName(stName);
        return courseBaseInfoDto;
    }

    //更新课程信息
    @Transactional
    @Override
    public CourseBaseInfoDto updateCourse(Long comId, EditCourseDto editCourseDto) {
        //本机构只能修改本机构课程
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (!courseBase.getCompanyId().equals(comId)) {
            XueChengPlusException.cast("本机构只能修改本机构课程！！");
        }
        //修改基本属性
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        updateById(courseBase);//更新课程基本信息
        //修改market属性
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        courseMarketMapper.updateById(courseMarket);

        return getCourseInfoDto(courseId);
    }

    private void saveMarket(CourseMarket courseMarket) {
        String charge = courseMarket.getCharge();//收费规则：付费否
        if(charge == null)throw new RuntimeException("插入异常");
        //无则插入，有则更新
        Long id = courseMarket.getId();
        CourseMarket m = courseMarketMapper.selectById(id);
        if(m == null){//无
            courseMarketMapper.insert(courseMarket);
        }else{//有
            BeanUtils.copyProperties(courseMarket, m);
            courseMarketMapper.updateById(m);
        }
    }
}
